<?php
function cache_get_anime($id){
	$id=intval($id);
	
	$cache=new cache;
	$dt=$cache->load("anime".$id,"anime");
	if(!$dt){
		$db=new db;
		$db->connect();
		$db->query("select * from anime where id=".$id);
		if($db->num_rows()>0){
			$dt=$db->fetchOne();
		
			
			
			 		
					 //Fetch tinh trang
					if($dt['tinhtrang']==1){	$dt['tinhtrang-text']="<a href='".HOME."status/truyen-hoan-thanh.html'>Full</a>";
					}else	if($dt['tinhtrang']==2){$dt['tinhtrang-text']= "<a href='".HOME."status/truyen-tam-ngung.html'>Tạm Ngưng</a>";
					}else{$dt['tinhtrang-text']= "<a href='".HOME."status/truyen-dang-cap-nhat.html.html'>Ongoing</a>";	}
					
					$html = str_get_html($dt['noidung']);
					$dt['noidung']=$html->plaintext;
					
					// Update table the loai cai coi
					 $sql="update anime_theloai_fk set views=".$dt['views'].",likes=".$dt['likes'].",comments=".$dt['comments'].",upload_time='".$dt['upload_time']."',tinhtrang=".$dt['tinhtrang'].",update_time='".$dt['update_time']."',tongsoep=".$dt['tongsoep'].",view_week=".$dt['view_week'].",view_month=".$dt['view_month'].",thanks=".$dt['thanks']." where anime_id=".$id ;
		
				$db->nonquery($sql);
				
				//Update ep_moinhat,tongsoep,link chapter moi nhat
				//ep_moinhaturl
				$db->query("select id,ten,seourl,ngaythem from chapterk2 where manga=".$dt['id']." order by ngaythem desc, thutu desc limit 0,1");
				$r1=$db->fetchOne();
				
				$db->query("select count(*) as num from chapterk2 where manga=".$id);
				$r2=$db->fetchOne();
				$dt['ep_num']=$r2['num'];
				$dt['ep_ngaythem']=$r1['ngaythem'];
				$dt['ep_moinhat']=$r1['ten'];
				$dt['ep_moinhaturl']=url_anime_episode($r1['id'],$r1['seourl'],$dt['alias']);
				$db->nonquery("update anime set tongsoep=".$dt['ep_num'].",ep_moinhat='".$dt['ep_moinhat']."',ep_moinhaturl='".$dt['ep_moinhaturl']."',update_time='".$dt['ep_ngaythem']."' where id=".$id);
				//echo $dt['ep_moinhat'];
					 

									   
									   
					 //GET ANIME LIEN QUAN-----
									
					if($dt['tags']!=''){
							   $db->query("select name,id,alias,hinhanh from anime where tags like'%".$dt['tags']."%' and id!= ".$id);
							   if($db->num_rows()>0){
								$dt['related']=$db->fetchAll();
											   }
								}
									   
									   //------ end get anime lien quan
					//Close ket noi db	
					if($dt['gtag']==0){
					$tagstring=tag1_generate($dt['name']);
					anime_tag1($dt['id'],$tagstring);
					$db=new db;
					$db->connect();
					$db->nonquery("update anime set gtag=1 where id=".$dt['id']);
					}
					//Generate tags phat da
								   
					 $db->close();
					 //Create tag--
					 $dt['data_tags']=tag1_link($dt['name']);
					 //------------
					 
					 //Fetch the loai de lay link
					$dt['theloai2']=get_anime_theloai($dt['theloai']);
						//Tag-
					$dt['tag']=anime_get_tag($dt['tags']);
					//GET EP CO THU TU LON NHAT RA
					
					//GET LIST CHUONG --------------------
					$db=new db;
					$db->connect();
					$db->query("select id,ten,seourl,index_show,ngaythem,uploader,solanxem from chapterk2 where manga=".$id." order by thutu desc");
					if($db->num_rows()>0){
						$dt['chapters']=$db->fetchAll();
					}
					$db->close();
					
				//tag3------
				//Tag3 update----------------
					if($dt['tag3']==''||$dt['tag3']==0){
							//Select 3 ep co thutu lon nhat
							$db=new db;
							$db->connect();
							$db->query("select id,ten,thutu from chapterk2 where manga=".intval($id)." order by thutu desc limit 0,5");
							
							$tt='';
									if($db->num_rows()>0){
										$dk=$db->fetchAll();
										foreach($dk as $row){
											if(strpos($row['ten'],$row['thutu'])!==false){
												$tt=$row['thutu'];
												break;
											}
										}
									}
							
							if($tt!=''){
								$tt=floor($tt);
								$db->nonquery("update anime set tag3=$tt where id=".intval($id));
								$db->close();
								tag3_generate($dt['name'],$tt,$dt['id']);
								//$cache=new cache;
								//$cache->flush("anime".$id,"anime");
							}else{
								$db->close();
							}
							
					}
	
					//get tag3
					$db=new db;
					$db->connect();
					$db->query("select name from anime_tag3 where anime_id=".intval($id));
					if($db->num_rows()>0){
						$tag=$db->fetchAll();
						foreach($tag as $rc){
						//Noi chuoi vao thoi
						$tags.=$rc['name'].",";
						
						}
					
						//echo $tags;
						$dt['tag3']=tag3_link($tags);
					}
					$db->close();
				//	echo $dt['tag3'];
				//End of tag3
					
			
			$cache->save("anime".$id,$dt,3600,"anime");
		}else{
			redirect(HOME);
			exit();
			} // End neu khong co anime nay
	}
/*	echo "<pre>";
	print_r($dt);
	echo "</pre>";*/
	
	return $dt;
}

function get_anime_theloai($str){
		
		$theloaiar=explode(",",$str);
		$str='';
		$str2='';
			$db2=new db;
			$db2->connect();
			foreach($theloaiar as $value ){
				$value=trim($value);
				$str.="<a href='".url_anime_theloai($value,khongdau($value))."'> <i class='fa fa-tags'></i> ".$value." </a> ";
				$str2.="<a href='".url_anime_theloai($value,khongdau($value))."'>".$value."</a>, ";
										
			}
			$str=substr($str,0,strlen($str)-1);
			$str2=substr($str2,0,strlen($str2)-1);
		$db2->close();
		$row['1']=$str;
		$row['2']=$str2;
		return $row;
}
function anime_get_tag($str){
			if($str){
					
					
							$tagar=explode(",",$str);
							$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_truyen_tag(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}

}





// SERIDATA



// Tag function -- Chua test dau nha-- khi add anime phai goi ham anime_tag1
function tag1_generate($str){
//Genrate tag from anime name
$string="doc truyen tranh,truyen tranh online,truyen tieng viet,truyen tranh,truyen tranh hay,truyen tranh vui,truyen tranh 18+,truyen tranh nhat ban,truyen tranh han quoc,doc truyen tranh online,doc truyen tranh,doc truyen tranh tinh cam,doc truyen tranh online tieng viet,doc truyen tranh online nhanh,doc truyen tranh online hay,doc truyen tranh online android,doc truyen tranh online iphone,doc truyen tranh online ipad,doc truyen tranh online 16+,doc truyen tranh online 18+,truyen tranh online nhat ban,truyen tranh online han quoc,doc truyen $str tieng viet,truyen $str full,doc truyen $str tron bo,$str full,$str tron bo";
return $string;
}
function tag1_link($str){
$string="doc truyen tranh,truyen tranh online,truyen tieng viet,truyen tranh,truyen tranh hay,truyen tranh vui,truyen tranh 18+,truyen tranh nhat ban,truyen tranh han quoc,doc truyen tranh online,doc truyen tranh,doc truyen tranh tinh cam,doc truyen tranh online tieng viet,doc truyen tranh online nhanh,doc truyen tranh online hay,doc truyen tranh online android,doc truyen tranh online iphone,doc truyen tranh online ipad,doc truyen tranh online 16+,doc truyen tranh online 18+,truyen tranh online nhat ban,truyen tranh online han quoc,doc truyen $str tieng viet,truyen $str full,doc truyen $str tron bo,$str full,$str tron bo";
	if($string){
					
					
							$tagar=explode(",",$string);
								$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_anime_tag(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}

}
function tag2_generate($str,$str2,$tt){
	$f=strpos($str2,$tt);
	if($f===false){
	//Not find thutu in chapter_name
	$string="$str $str2,$str $str2 tieng viet";
	}else{
	$string="$str  chap $tt,$str $tt,$str chap $tt tieng viet,$str $tt tieng viet,doc truyen $str $tt tieng viet,doc truyen $str chap $tt tieng viet";
	}
	
	
	
return $string;
}

function tag2_generates($str,$tt){

	$string="$str  chap $tt,$str $tt,$str chap $tt tieng viet,$str $tt tieng viet,doc truyen $str $tt tieng viet,doc truyen $str chap $tt tieng viet";
	
	
	
	
return $string;
}
function tag2_link($str,$str2,$tt){
	$f=strpos($str2,$tt);
	if($f===false){
	//Not find thutu in chapter_name
	$string="$str $str2,$str $str2 tieng viet";
	}else{
	$string="$str  chap $tt,$str $tt,$str chap $tt tieng viet,$str $tt tieng viet,doc truyen $str $tt tieng viet,doc truyen $str chap $tt tieng viet";
	}
	if($string){
					
					
							$tagar=explode(",",$string);
								$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_anime_tag2(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}
}
function tag3_generate($str,$num,$anime_id){

	//Check num delete-----
	$db=new db;
	$db->connect();
	$mnum=$num-2;
	$db->nonquery("delete from anime_tag3 where anime_id=$anime_id and thutu <".$num);
	$num1=$num+1;
	$num2=$num+2;
	$num3=$num+3;
	
	//Tag level 1
	$db->query("select id from anime_tag3 where anime_id=$anime_id and thutu=".$num1);
	if($db->num_rows()==0){
	
	$str1=tag2_generates($str,$num1);
	//echo $str1;
	anime_tag3($num1,$anime_id,$str1);
	}
	//Tag level 2
	$db->query("select id from anime_tag3 where anime_id=$anime_id and thutu=".$num2);
	if($db->num_rows()==0){
	
	$str2=tag2_generates($str,$num2);
	anime_tag3($num2,$anime_id,$str2);
	}
	//Tag level 3
	$db->query("select id from anime_tag3 where anime_id=$anime_id and thutu=".$num3);
	if($db->num_rows()==0){
	
	$str3=tag2_generates($str,$num3);
	anime_tag3($num3,$anime_id,$str3);
	}
	
//	echo mysql_error();
	$db->close();
	
	//Xong roi , thiet la vai l qua di

}

function tag4_link($string){


		if($string){
					
					
							$tagar=explode(",",$string);
								$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_anime_tag4(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}

}

function tag3_link($string){


		if($string){
					
					
							$tagar=explode(",",$string);
								$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_anime_tag3(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}

}

function anime_tag1($id,$str){
	//Insert anime tag
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											if($tag){
											$db->query("select * from anime_tag1 where alias ='".$tag."'");
											
														if($db->num_rows()>0){
															$row=$db->fetchOne();
														
															
															//Handle tag_post
															$db->query('select * from anime_tag1_fk where anime_id='.$id.' and tag_id='.$row['id']);
															
																if($db->num_rows()>0){
																
																}else{
																	
																 	$db->nonquery("insert into anime_tag1_fk(tag_id,anime_id) values(".$row['id'].",".$id.")");
																
																}
														
														}else{
														
															$db->nonquery("insert into anime_tag1(name,alias) values('".$value."','".$tag."')");
														
														
															$tag_id=$db->get_insert_id();
															$db->nonquery("insert into anime_tag1_fk(tag_id,anime_id) values(".$tag_id.",".$id.")");
															
															
														}
											}// Neu tag ko rong
										}
										
						$db->close();
							
				}

}

function anime_tag2($epid,$id,$str){
	//Insert anime tag
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											
											$db->query("select * from anime_tag2 where ep_id=$epid and alias ='".$tag."'");
											
														if($db->num_rows()>0){
															$row=$db->fetchOne();
														
															
															
														
														}else{
														
															$db->nonquery("insert into anime_tag2(name,alias,ep_id,anime_id) values('".$value."','".$tag."',".$epid.",".$id.")");
															
															
															
														}
										}
						$db->nonquery("update chapterk2 set gtag=1 where id=".$epid);				
						$db->close();
							
				}

}

function anime_tag3($thutu,$id,$str){
	//Khong close db de con su dung trong function tag3_generate
	//Insert anime tag
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											
											$db->query("select * from anime_tag3 where alias ='".$tag."'");
											
														if($db->num_rows()>0){
															}else{
												$db->nonquery("insert into anime_tag3(name,alias,thutu,anime_id) values('".$value."','".$tag."',".$thutu.",".$id.")");
												
														}
										}
										
						
							
				}

}


function static_admin(){
	//--------------MANGA------------------
	//			--Admin có tất car persmission
	//			--Smod,Uploader được duyệt truyện và fix chap
			
						$cache=new cache;
						$dt=$cache->load('static','home');
						if(!$dt){
							//Count số cẫn xử lý
						$admin=0;
						$smod=0;
						$uploader=0;
						$db=new db;
						$db->connect();
								//-----Duyet Anime
						$db->query("select id from anime where duyet=0");
						$dt['duyet_anime']= $db->num_rows();
						$admin=$admin+$dt['duyet_anime'];
						$smod=$smod+$dt['duyet_anime'];
								//-----Xoa anime
						$db->query("select id from anime where xoa=1");
						$dt['xoa_anime']=$db->num_rows();
						$admin=$admin+$dt['xoa_anime'];
						//DUYET VA XOA FANSUB
						//XOA EPISODE
						
						$db->query("select id from chapterk2 where xoa=1");
						$dt['xoa_episode']=$db->num_rows();
						$admin=$admin+$dt['xoa_episode'];
						$smod=$smod+$dt['xoa_episode'];
						
					
					
							//----------Report Chap bị lỗi
						$db->query("select id from report_truyen where xuly=0");
						$dt['reporttruyen']=$db->num_rows();
						$k=	$dt['reporttruyen'];
						$admin=$admin+$k;
						$smod=$smod+$k;
						$uploader=$uploader+$k;
						
						$dt['uploader']=$k;
						$dt['smod']=$smod;
						$dt['admin']=$admin;
							//-----------BLOG HANDLE ---------------
								//---------CHUA DUYET TOPIC -------
						$db->query("select id from blog_post where status=0");
						$dt['blogduyet']=$db->num_rows();
						$admin=$admin+$dt['blogduyet'];	
						$smod=$smod+$dt['blogduyet'];
						$modforum=$dt['blogduyet'];
								// Comment post ---------------
										//---Hide Comment
						$db->query("select id from blog_comment where hide=1");
						$dt['bloghide']=$db->num_rows();
						$admin=$admin+$dt['bloghide'];	
						$smod=$smod+$dt['bloghide'];
						$modforum=$dt['bloghide'];
										//---Hide Comment
						$db->query("select id from blog_comment where report > 0");
						$dt['blogreport']=$db->num_rows();
						$admin=$admin+$dt['blogreport'];	
						$smod=$smod+$dt['blogreport'];
						$modforum=$dt['blogreport'];
						
						
						$db->close();
						$cache->save('static',$dt,120,'home');
						}
						?>
				
                    			<li class="dropdown">
						<a class="btn dropdown-toggle" data-toggle="dropdown" >
							<i class="fa fa-bell-o"></i> Xử Lý <span class="badge">
						<?php  if($_SESSION['user']['level']==5){ 
									echo $dt['uploader'];
								}else
								if($_SESSION['user']['level']==2){
									  echo $dt['smod'];
								}else{ 
								echo $dt['admin'];
								} ?>
                                </span>
						</a>
                        
                      <ul class="dropdown-menu">
                      <li role="presentation" class="dropdown-header">Manga</li>
                        
						<?php
							if($_SESSION['user']['level']==1){
								//----Admin boss --- ?>
<li><a href="<?php echo HOME;?>index.php?module=manage&act=manga&opt=common&type=manga&ext=duyet">Duyệt Truyện <span class="badge"><?php echo $dt['duyet_anime'];?></span></a></li>
<li><a href="<?php echo HOME;?>index.php?module=manage&act=manga&opt=common&type=manga&ext=xoa">Xóa Truyện <span class="badge"><?php echo $dt['xoa_anime'];?></span></a></li>
<li><a href="<?php echo HOME; ?>index.php?module=manage&act=manga&opt=common&type=chapter&ext=xoa">Xóa Chap <span class="badge"><?php echo $dt['xoa_episode']; ?></span></a></li>
<li><a href="<?php echo HOME; ?>index.php?module=manage&act=manga&opt=common&type=report&ext=xuly">Report Chap <span class="badge"><?php echo $dt['reporttruyen'];?></span></a></li>
                                <?php //End admin boss
							}
						?>	
                            
                      <?php
							if($_SESSION['user']['level']==2||$_SESSION['user']['level']==5){
								//----SMOD hoặc Uploader--- ?>
<li><a href="<?php echo HOME;?>index.php?module=manage&act=manga&opt=common&type=manga&ext=duyet">Duyệt Truyện <span class="badge"><?php echo $dt['duyet_anime'];?></span></a></li>
<li><a href="<?php echo HOME; ?>index.php?module=manage&act=manga&opt=common&type=report&ext=xuly">Report Chap <span class="badge"><?php echo $dt['reporttruyen'];?></span></a></li>                                <?php //End admin boss
							}
						?>	      
                            <!-- Section Manage Blog Post -->
                            <li role="presentation" class="divider"></li>
                            <li role="presentation" class="dropdown-header">Blog Moderator</li>  
                            
                            		<?php
							if($_SESSION['user']['level']==1){
								//----Admin boss --- ?>
<li><a href="<?php echo HOME;?>index.php?module=manage&act=blog&opt=post&ext=duyet">Duyệt Topic <span class="badge"><?php echo $dt['blogduyet'];?></span></a></li>
<li><a href="<?php echo HOME;?>index.php?module=manage&act=blog&opt=post_comment&ext=hide">Hide Comment <span class="badge"><?php echo $dt['bloghide'];?></span></a></li>
<li><a href="<?php echo HOME; ?>index.php?module=manage&act=blog&opt=post_comment&ext=report">Report Comment <span class="badge"><?php echo $dt['blogreport']; ?></span></a></li>
                             <?php //End admin boss
							}
						?>	
                            
                            </ul>
					</li>
                          <?php
}
function url_anime($id,$str){
	
		//return HOME."index.php?module=truyen&act=view&id=".$id;
		return HOME.''.$id.'/'.$str.'.html';
	
}
function url_anime_theloai($id,$str){
	
		return HOME.$str.".html";
	
}
function url_anime_episode($id,$str1,$str2=''){
//return HOME."index.php?module=truyen&act=chuong&id=".$id;
return HOME.$id.'/'.$str1.'/';

}

function url_anime_tag($str){
		return HOME."tag/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_anime_tag2($str){
		return HOME."tag2/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_anime_tag3($str){
		return HOME."tag3/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_anime_tag4($str){
		return HOME."tag4/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}

function anime_theloai($id,$str){
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
												/*	$tag=intval($value);
													//Handle tag_post
															$db->query('select * from anime_theloai_fk where anime_id='.$id.' and theloai_id='.$tag);
																if($db->num_rows()>0){
																	}else{
																	
																 	$db->nonquery("insert into anime_theloai_fk(theloai_id,anime_id) values(".$tag.",".$id.")");
																	echo mysql_error();
															}
												*/
												//Start code moi
												if($value!=''){
												$tag=khongdau(trim($value));
												$db->query("select * from anime_theloai where alias ='".$tag."'");
											
														if($db->num_rows()>0){
															$row=$db->fetchOne();
														
															
															//Handle tag_post
															$db->query('select * from anime_theloai_fk where anime_id='.$id.' and theloai_id='.$row['id']);
														
																if($db->num_rows()>0){
																
																}else{
																	
																 	$db->nonquery("insert into anime_theloai_fk(theloai_id,anime_id) values(".$row['id'].",".$id.")");
															
																}
														
														}else{
														
														/*	$db->nonquery("insert into anime_theloai(name,alias) values('".$value."','".$tag."')");
															$tag_id=$db->get_insert_id();
															$db->nonquery("insert into anime_theloai_fk(theloai_id,anime_id) values(".$tag_id.",".$id.")");
															*/
															
														}
												}//End of $value!=''
												
												//End code moi
										}
										
						$db->close();
							
				}

}



function anime_theloai2($str){
			if($str){
					
						$db=new db;
						$db->connect();
						$db->query("select id,name from anime_theloai");
						$dt=$db->fetchAll();
						$str2=$str;
						foreach($dt as $row){
							$name=$row['name'];
							if($name!='')
							if(stripos($str,$name)!==false)
							{
								//Find the loai nay
								$dt2[]=trim($name);
								// replace this the loai
								$str2=str_replace($name,"",$str2);
								
							}
							
						}
						
					/*	if(trim($str2)!=''){
								$ar=explode(" ",$str2);
								foreach($ar as $row){
									if($row!=''){
									$dt2[]=trim($row);
									}
								}
						}*/
						
						//$dt2 la mang du lieu do;
						
						if(count($dt2)>0){
						$str=implode(',',$dt2);
						}
						
						$db->close();
			}
				return $str;

}


function anime_theloai_tag($id,$str){
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											
												//Start code moi
												if($value!=''){
												$tag=khongdau(trim($value));
											
												$db->query("select * from anime_tag4 where alias ='".$tag."'");
											
														if($db->num_rows()>0){
																										
														}else{
												$db->nonquery("insert into anime_tag4(name,alias,theloai_id) values('".$value."','".$tag."',".$id.")");
														}
												}//End of $value!=''
												
												//End code moi
										}
										
						$db->close();
							
				}

}

//Manga function ------------

function manga_get_update($number){
	$cache=new cache;
	$data2=$cache->load('manga_get_update'.$number);
	if(!$data2){
		$db=new db;
		$db->connect();
		$db->query("SELECT mg.id, mg.name,mg.alias,chap.ten, chap.id as chapid,chap.hot,chap.new, chap.seourl,chap.index_show,chap.ngaythem
								FROM chapterk2 AS chap, anime AS mg
								WHERE  chap.index_show!='' and chap.manga = mg.id
								ORDER BY chap.ngaythem desc,chap.id desc
								LIMIT 0 , ".$number);
				$dt=$db->fetchAll();
			foreach($dt as $row){
				$row['hinhanh']=preg_replace('/https/','http',$row['hinhanh']); 
				$row['mgurl']=url_anime($row['id'],$row['seo_tieude']);
				 $row['chapurl']=url_anime($row['chapid'],$row['seourl']);
				 $data[]=$row;
			}
			
			//Foreach data phat đa
				$ngay=$data[0]['ngaythem'];
							$row2['ngay']=$ngay;
							$data2=array();
							foreach($data as $row){
									if($ngay!=$row['ngaythem']){
										
												$data2[]=$row2;  //---------Clear row 2
												$ngay=$row['ngaythem'];
												$row2=array();
												$row2['ngay']=$ngay;
												$row2['data'][]=$row;
										
									}else{
											$row2['data'][]=$row;
									}
								
							}
								$data2[]=$row2;
			
			//End foreach data
	$cache->save("manga_get_update".$number,$data2,300);							
	}
	
	
	return $data2;
}

function get_manga_list($dt){
			foreach($dt as $row){
				
				$row['mgurl']=url_anime($row['id'],$row['seo_tieude']);
				 $row['chapurl']=url_anime($row['chapid'],$row['seourl']);
				 $data[]=$row;
			}
			
			//Foreach data phat đa
				$ngay=$data[0]['ngaythem'];
							$row2['ngay']=$ngay;
							$data2=array();
							foreach($data as $row){
									if($ngay!=$row['ngaythem']){
										
												$data2[]=$row2;  //---------Clear row 2
												$ngay=$row['ngaythem'];
												$row2=array();
												$row2['ngay']=$ngay;
												$row2['data'][]=$row;
										
									}else{
											$row2['data'][]=$row;
									}
								
							}
									$data2[]=$row2;
								return $data2;
								
}


function cache_get_ep($id){
	
	$id=intval($id);
	$cache=new cache;
	$sub=$id%100;
	//Dau tien la check ngay them manga nay bao lau roi
	$db=new Model;
	
	$db->query("select * from chapterk_time where chap_id =".$id);
	if($db->num_rows()==0){
			$db->query("select ngaythem from chapterk2 where id=".$id);
			$r1=$db->fetchOne();
			$datam=array("chap_id"=>$id,"time"=>$r1['ngaythem']);
			$db->insert("chapterk_time",$datam);
			$ngaythem=$r1['ngaythem'];
	}else{
		  $r1=$db->fetchOne();
		  $ngaythem=$r1['time'];	
	}
	//So sanh ngay
	if($ngaythem > date('Y-m-d',strtotime('-1 day'))){
	
	//Chapter nay moi add trong vong 2 ngay, nen cache 
	$try_cache=true;
	}else{$ry_cache=false; }
	//
	if($try_cache){

	$data=$cache->load('manga_get_chapter_detail'.$id,'chapter/'.$sub);
	}else{
	
	$data=false;
	}
	
	if(!$data){
	
			$mg=new Model;
			//---------- GET MANGA INFORMATION
			$mg->where="id= $id";
			$mg->query("select * from chapterk2 where id=".$id);
			$row=$mg->fetchOne();	
			$row['url']=url_anime_episode($row['id'],$row['seourl']);
			
			//-------- CHECK AND FIX IMAGE LINK -----------------
	
					
						if($row['op']==1){
						
							$db->query("select * from chapterk_content where chap_id=".$id);
							//echo mysql_error();
							if($db->num_rows()>0){
								$r2=$db->fetchOne();
								
								//Chapterk3_content dung de chua link remote upload len picasa cua image co tren server Manga24h-----
								$db->query("select * from chapterk3_content where chap_id=".$id);
								$num=$db->num_rows();
							//	if($r2['server']=='manga24h.com'&&$num>0&$r2['check_link']==1&&$r2['check_error']==0){
								if($r2['server']=='manga24h.com'&&$num>0){
								
									//GET TU TABLE CHAPTERK3_CONTENT
								
									$r2=$db->fetchOne();
									$row['chapter_link']=unserialize($r2['picasa']);
									$row['chapter_page']=$r2['chap_page'];
								}else{
								
											$row['chapter_link']=unserialize($r2['chap_content']);
											$link=$row['chapter_link'][0];
											
											
											if(strpos($link,'vnsharing')!==false){
											$r5['server']='manga24h.com';
											$r5['error']=0;
											}else
											if(strpos($link,'manga24h.com')!==false){
											$r5['server']='manga24h.com';
											$r5['error']=0;
											}else
											if(strpos($link,'upimgs.org')!==false){
											$r5['server']='upimgs';
											$r5['error']=1;
											}else
											if(strpos($link,'zdn.vn')!==false){
											$r5['server']='zing';
											$r5['error']=0;
											}
											else
											if(strpos($link,'upanh.com')!==false){
											$r5['server']='upanh';
											$r5['error']=1;
											}
											else
											if(strpos($link,'blogspot.com')!==false){
											$r5['server']='blogspot';
											$r5['error']=0;
											}else{
											$r5['server']='khac';
											$r5['error']=0;
											}
											
											
											
											$row['chapter_page']=$r2['chap_page'];
											
											
											$db->where("chap_id=".$id);
											$db->update("chapterk_content",$r5);
								}
								
							}
							
						}else{
							//Start get link page 
							//if($row['upload']==1 && $row['zing']==0 && $row['blog']==0 && $row['upanh']==0)
							if(0)
							{	
								
								
								$db->query("select * from mangadata where id=".$row['id']);
								$row_data=$db->fetch();
								$row_image=unserialize($row_data[data]);
								$h=$row_image['pages'];
								natsort($row_image['images']);
								$image=$row_image['images'];
								$image2=array();
								foreach($image as $value)
								{
								$image2[]="http://data2.manga24h.com/".$value;
								}
								
								$row['chapter_link']=$image2;
								$row['chapter_page']=	$h;	
								
								//Else of getlink	
							}else{
								
								
								//=========================Lay link image tu ngoai vao================
								$row['chapter_link']=array();
								$source=$row['source'];
								
								
									
								
								preg_match_all('/(img|src)\=(\"|\')[^\"\'\>]+/i', $source, $media);
								$datasource=preg_replace('/(img|src)(\"|\'|\=\"|\=\')(.*)/i',"$3",$media[0]);
								$images = array();
								$h=0;
								foreach($datasource as $url)
								{
											//preplace zing link......
														$new=preg_replace('/img.photo.zing.vn/',"d.f2.photo.zdn.vn",$url);
											  		   $bl=preg_replace('/lh3.ggpht.com/',"1.bp.blogspot.com",$new);
														$bl1=preg_replace('/lh4.ggpht.com/',"2.bp.blogspot.com",$bl);
														$bl2=preg_replace('/lh5.ggpht.com/',"3.bp.blogspot.com",$bl1);
														$bl3=preg_replace('/lh6.ggpht.com/',"4.bp.blogspot.com",$bl2);
														$bl4=preg_replace('/https:\/\/lh3.googleusercontent.com/',"http://3.bp.blogspot.com",$bl3);
														$bl5=preg_replace('/https:\/\/lh4.googleusercontent.com/',"http://2.bp.blogspot.com",$bl4);
														$bl6=preg_replace('/https:\/\/lh5.googleusercontent.com/',"http://1.bp.blogspot.com",$bl5);
														$bl7=preg_replace('/https:\/\/lh6.googleusercontent.com/',"http://4.bp.blogspot.com",$bl6);
													
														$bl8=preg_replace('/http:\/\/lh3.googleusercontent.com/',"http://3.bp.blogspot.com",$bl7);
														$bl9=preg_replace('/http:\/\/lh4.googleusercontent.com/',"http://2.bp.blogspot.com",$bl8);
														$bl10=preg_replace('/http:\/\/lh5.googleusercontent.com/',"http://1.bp.blogspot.com",$bl9);
														$bl11=preg_replace('/http:\/\/lh6.googleusercontent.com/',"http://4.bp.blogspot.com",$bl10);
														
														$new2=preg_replace('/data.manga24h.com\/manga/',"data2.manga24h.com/manga1",$bl11);
														$new3=preg_replace('/media3.manga24h.com/',"data2.manga24h.com",$new2);
														$new4=preg_replace('/data.manga24h.com\/data/',"data2.manga24h.com/data",$new3);
														$new5 = preg_replace('/\/s[0-9]*\//', '/s0/',$new4);
														
														
														$pos = strpos($new5, "blogspot.com");
														if ($pos === false) {
														   
														} else {
																	if(!preg_match("/\/s[0-9]*\//",$new5)&&!preg_match("/\/h[0-9]*\//",$new5)&&!preg_match("/\/w[0-9]*\//",$new5)){
																	$new5 = preg_replace('/\/[a-z0-9-_%\.]*\.(jpg|png|gif|jpeg)/i', '/s0/1.jpg',$new5);
																	}
																																		
														}
																												
																												
														
														
														array_push($row['chapter_link'],$new5);
														$h++;
	

											
		
									
	
								}
								$row['chapter_page']=$h;	
							
							
							} //End of else getlink
							
							
							
							// GET LINK OKE ROI, GIO INSERT VAO CHAPTERK_CONTENT
							$db->nonquery("delete from chapterk_content where chap_id=".$id);
							$datan=array("chap_content"=>serialize($row['chapter_link']),"chap_id"=>$id,"chap_page"=>$row['chapter_page']);
							$db->insert("chapterk_content",$datan);
							$db->nonquery("update chapterk2 set op=1 where id=".$id);
	}//End of else op
	
							
							$data=$row;
			
		//SET CACHE KHI TRY CACHE ==TRUE	
		if($try_cache){
		
			$cache->save("manga_get_chapter_detail".$id,$data,3600,'chapter/'.$sub);	
		}
	}
	
	return $data;
	
	

}
function gglink($link){
return preg_replace('/https:\/\/(.*?)googleusercontent\.com/', 'http://3.bp.blogspot.com', $link);
}
//End of manga function